package org.javaforever.cookieshop.shiro;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import com.alibaba.fastjson.JSON;

public class ShiroPermsAuthorizationFilter extends PermissionsAuthorizationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", "true");
        res.setContentType("application/json; charset=utf-8");
        res.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = res.getWriter();
        Map<String, Object> map= new HashMap<>();
        // 没有认证,先返回未认证的json
        if (subject.getPrincipal() == null) {
            map.put("success", false);
            map.put("noAuth",true);
            map.put("error", "未登录");
        } else {
            map.put("success", false);
            map.put("noAuth",true);
            map.put("error", "No privilege.");
        }
        writer.write(JSON.toJSONString(map));
        writer.flush();
        writer.close();
        return false;
    }

}
